package com.edroid.droidhelper.pc.app;

import java.awt.Font;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Enumeration;

import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.FontUIResource;

import com.edroid.droidhelper.pc.view.ErrorDialog;

public class SwingApplication extends Application {
	static final String[] UIS = {
		"OptionPane.font",
		"Menu.font",
		"Tree.font",
		"ScrollPane.font",
		"CheckBoxMenuItem.font",
		"TitledBorder.font",
		"Viewport.font",
		"MenuItem.acceleratorFont",
		"RadioButton.font",
		"Button.font",
		"CheckBox.font",
		"RadioButtonMenuItem.acceleratorFont",
		"TabbedPane.font",
		"TextField.font",
		"Slider.font",
		"TextArea.font",
		"Panel.font",
		"EditorPane.font",
		"CheckBoxMenuItem.acceleratorFont",
		"Table.font",
		"Menu.acceleratorFont",
		"ProgressBar.font",
		"ToggleButton.font",
		"DesktopIcon.font",
		"InternalFrame.titleFont",
		"PasswordField.font",
		"TableHeader.font",
		"FormattedTextField.font",
		"MenuBar.font",
		"ColorChooser.font",
		"RadioButtonMenuItem.font",
		"ComboBox.font",
		"TextPane.font",
		"List.font",
		"MenuItem.font",
		"Spinner.font",
		"ToolBar.font",
		"PopupMenu.font",
		"ToolTip.font",
		"Label.font"
	};
	ErrorDialog jd = null;

	public SwingApplication(boolean nativeLook) {
		try {
			if(nativeLook)
				UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			
//			long t0 = System.currentTimeMillis();
			Font deFont = Font.decode("Microsoft YaHei-PLAIN-16");
//			initGlobalFontSetting();
//			UIManager.getLookAndFeelDefaults().put("defaultFont", deFont);
			
			setGlobalFont(new FontUIResource(deFont));
			
//			System.out.println("time=" + (System.currentTimeMillis() - t0));
//			initGlobalFontSetting(Font. new Font("微软雅黑", Font.PLAIN, 16));
		} catch(Exception ex) {
			throw new RuntimeException(ex);
		}
	}
	
	public void setGlobalFont(FontUIResource fnt) {
		for(String s : UIS) {
			UIManager.put(s, fnt);
		}
	}
	
	/**
	 * 改全局字体
	 * @param fnt
	 */
	public static void initGlobalFontSetting(Font fnt) {
		FontUIResource fontRes = new FontUIResource(fnt);
		
		Enumeration<Object> keys = UIManager.getDefaults().keys();
		while(keys.hasMoreElements()) {
			Object key = keys.nextElement();
			if (UIManager.get(key) instanceof FontUIResource)
				UIManager.put(key, fontRes);
		}
	}
	
	@Override
	protected void handleException(Thread thread, Throwable ex) {
		try {
			StringWriter sw = new StringWriter();
			ex.printStackTrace(new PrintWriter(sw));
			if(sw.toString().contains("SynthTreeUI"))
				return;
			ex.printStackTrace(System.err);
			
			if(jd != null && jd.isVisible())
				return;
			
			jd = new ErrorDialog(ex);
			SwingUtilities.invokeLater(new Runnable() {
				
				public void run() {
					jd.setVisible(true);
				}
			});
		} catch(Exception ex2) {
			// ignored
		}
	}
}
